<template>
  <div>
    <berad-crumb name1="权限管理" name2="角色列表"></berad-crumb>
    <el-card class="box-card">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="8">
          <el-input
            v-model="usersParams.query"
            :clearable="true"
            placeholder="请输入内容"
            @click="getUsersList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 渲染数据 -->
      <el-table border :data="userList" style="width: 100%; margin-top: 10px; margin-bottom: 20px">
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scoped">
            <div>
              <el-switch v-model="scoped.row.mg_state" @change="userStateChange(scoper.row)"></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scoped">
            <div>
              <el-tooltip content="修改用户信息" placement="top-start">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editShowDialog(scoped.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除用户" placement="top-start">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deletUserInfoById(scoped.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="权限分配" placement="top-start">
                <el-button type="primary" icon="el-icon-setting" circle></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersParams.pagenum"
        :page-sizes="[1, 2, 5, 8]"
        :page-size="usersParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        @click="addUserDialogClear"
      >
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="30%">
        <el-form ref="editForm" :model="editFormData" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editFormData.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :rules="addUserFormRules.email">
            <el-input v-model="editFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" :rules="addUserFormRules.mobile">
            <el-input v-model="editFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">修改用户信息</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import BeradCrumb from "@/components/common/breadcrumb/BeradCrumb.vue";
import {
  users_list_req,
  users_state_req,
  users_info_id_req,
  add_user_req,
  edit_users_info_req,
  // delete_users_req
} from "@/api/users";
export default {
  created() {
    const userParamsS = JSON.parse(sessionStorage.getItem("usersParams"));
    if (userParamsS) {
      this.usersParams = userParamsS;
    } else {
      this.usersParams = {
        query: "",
        pagenum: 1,
        pagesize: 5
      };
    }
  },

  data() {
    //邮箱
    let checkEmail = (rule, value, callback) => {
      const emailReg = /^\w+@\w+(\.\w+)+$/;
      if (emailReg.test(value)) {
        return callback();
      }
      //不符合
      return callback(new Error("请输入合法邮箱"));
    };
    //手机号
    let checkMobile = (rule, value, callback) => {
      const mobileReg = /^1[3456789]\d{9}$/;
      if (mobileReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      usersParams: {},
      userList: [],
      total: 0,

      addDialogVisible: false,

      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },

      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在3到20个字符",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur"
          }
        ]
      },
      // 控制修改对话框的显示隐藏
      editDialogVisible: false,
      // editForm表单的数据
      editFormData: {}
    };
  },
  components: {
    BeradCrumb
  },
  mounted() {
    this.getUsersList();
  },
  methods: {
    async getUsersList() {
      const result = await users_list_req({
        method: "get",
        url: "users",
        params: this.usersParams
      });
      //   console.log(result);
      if (result.meta.status == 200) {
        this.userList = result.data.users;
        this.total = result.data.total;
      }
    },
    // 当改变一页有多少条数据时，handleSizeChange，返回的参数 最新的一页有多少条数据
    handleSizeChange(newPageSize) {
      console.log(newPageSize);
      this.usersParams.pagesize = newPageSize;
      sessionStorage.setItem("usersParams", JSON.stringify(this.usersParams));
      this.getUsersList();
    },
    // 当点击页码 触发handleCurrentChange 参数新的页面
    handleCurrentChange(newPageNum) {
      console.log(newPageNum);
      this.usersParams.pagenum = newPageNum;
      sessionStorage.setItem("usersParams", JSON.stringify(this.usersParams));
      this.getUsersList();
    },
    // swicth组件状态改变触发的函数
    async userStateChange(newState) {
      console.log(newState);
      const result = await users_state_req({
        method: "put",
        url: `users/${newState.id}/state/${newState.mg_state}`
      });
      console.log(result);
      if (result.meta.status != 200) {
        newState.mg_state = !newState.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      return this.$message({
        type: "success",
        message: "更新用户状态成功"
      });
    },
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        console.log(valid);
        // 当验证失败 valid false 到此为止 不往下执行
        if (!valid) return;
        // 当验证成功 valid true
        // 发送添加用户的ajax
        const result = await add_user_req({
          method: "post",
          url: "users",
          data: this.addUserForm
        });
        console.log(result);
        if (result.meta.status != 201) {
          return this.$message.error("添加用户失败");
        }
        // 关掉添加用户的对话窗
        this.addDialogVisible = false;
        // 添加用户之后需要有一个更新所有数据的操作
        this.getUsersList();
        return this.$message.success("添加用户成功");
      });
    },
    // 清除form表单的数据
    addUserDialogClear() {
      this.$refs.addUserFormRef.resetFields();
    },
    // 点击users页面上的修改用户按钮触发的事件
    async editShowDialog(userInfo) {
      console.log(userInfo);
      // 展示用户修改的对话框
      // 根据id查询到用户的信息
      // 请求数据和显示对话框谁在上谁在下 数据请求再上

      const result = await users_info_id_req({
        method: "get",
        url: `users/${userInfo.id}`
      });
      console.log(result);
      if (result.meta.status !== 200) {
        return this.$message.error("查询数据失败");
      }
      this.editFormData = result.data;

      this.editDialogVisible = true;
    },
    // 收集到修改的用户信息 前台验证成功之后 发送请求提交服务器
    editUserInfo() {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return;
        const result = await edit_users_info_req({
          method: "put",
          url: `users/${this.editFormData.id}`,
          data: this.editFormData
        });
        // put请求的参数写到data当中
        console.log(result);
        if (result.meta.status !== 200) {
          return this.$message.error("修改用户信息失败");
        }
        // 更新table当中的数据
        this.getUsersList();
        this.editDialogVisible = false;
        return this.$message.success("修改用户信息成功");
      });
    },
    // 删除用户信息
    async deletUserInfoById(id) {
      console.log(id);
      //  删除逻辑：
      //           1.确认  您确认要删除xxx  删除 取消
      //           2. 确认删除 获取id 发送ajax删除服务器数据 重新渲染table
      //           3.取消

      // 但凡是promise对象 可以通过async和await将其转变为同步 通过catch处理错误
      const resultConfirem = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(resultConfirem);

      // console.log("提交代码测试");
      // console.log("提交代码测试");
      // console.log("提交代码测试");
    },
  }
};
</script>

<style lang="scss" scoped>
</style>